import clientAPI.ServerMessage;

public class Map {
	Integer map[][];
	int height, width;
	Robot r;
	int scale = 1;
	ThreadCommunication comm;
	
	public Map(int width, int height, ThreadCommunication comm) {
		this.comm = comm;
		this.width = width;
		this.height = height;
		map = new Integer[width][height];
		for (int i=0;i<width;i++)
			for (int j=0;j<height;j++)
				map[i][j] = null;
		r = new Robot(width*scale/2, height*scale/2,0);
	}
	
	private void setRobotPosition(int x, int y, boolean reInit){
		System.out.println("setting robot position");
		int rX = r.getX();
		int rY = r.getY();
		int dX = x - rX;
		int dY = y - rY;
		int tX = rX;
		int tY = rY;
		int max = Math.max(Math.abs(dX), Math.abs(dY));
		ServerMessage sMsg;
		if (!reInit){
			for (int i = 0;i<max/scale;i++){
				tX = (int)(rX + (i*dX)/max);
				tY = (int)(rY + (i*dY)/max);
				map[tX/scale][tY/scale] = 1;
				sMsg = new ServerMessage(1, tX/scale, tY/scale);
				comm.addServerMessage(sMsg);
			}
			map[x/scale][y/scale] = 3;
			sMsg = new ServerMessage(3, x/scale, y/scale);
			comm.addServerMessage(sMsg);
		}
		map[x/scale][y/scale] = 3;
		r.setPosition(x,y);
	}
	
	public void addObstacleRelRobot(int distance, int angle){
		System.out.println("D: " + distance + " A: " + angle);
		int objX, objY;
		int dX, dY, tX, tY;
		ServerMessage sMsg;
		int rAngle = angle+r.getFacingAngle();
		objX = r.getX() + (int)(Math.cos(Math.toRadians(rAngle))*distance);
		objY = r.getY() + (int)(Math.sin(Math.toRadians(rAngle))*distance);
		dX = r.getX() - objX;
		dY = r.getY() - objY;
		int max = Math.max(Math.abs(dX), Math.abs(dY));
		System.out.println("Max: " + max/scale + "  dX: " + dX + "  dY: "+ dY);
		for (int i = 0;i<max/scale;i++){
			System.out.println("Loop " + i);
			tX = (int)(r.getX() - dX*(double)(i/(double)(max/scale)));
			tY = (int)(r.getY() - dY*(double)(i/(double)(max/scale)));
			map[tX/scale][tY/scale] = 1;
			sMsg = new ServerMessage(1, tX/scale, tY/scale);
			comm.addServerMessage(sMsg);
		}

		objX = objX/scale;
		objY = objY/scale;
		if (objX > 0 && objX < width && objY > 0 && objY < height){
			sMsg = new ServerMessage(2, objX, objY);
			comm.addServerMessage(sMsg);
			map[objX][objY] = 1;
		}
	}
	
	public void addObstacleOnPosition(int x, int y){
		ServerMessage sMsg = new ServerMessage(1, x/scale, y/scale);
		comm.addServerMessage(sMsg);
		map[x/scale][y/scale] = 1;
	}
	
	public void reInitRobot(int x, int y) {
		setRobotPosition(x, y, true);
	}
	
	public void resendRobotPosition(){
		ServerMessage sMsg = new ServerMessage(3, r.getX()/scale, r.getY()/scale);
		comm.addServerMessage(sMsg);
	}
	
	public void moveRobot(int distance, int angle){
		int nX, nY;
		nX = r.getX() + (int)(Math.cos(Math.toRadians(r.getFacingAngle()))*distance);
		nY = r.getY() + (int)(Math.sin(Math.toRadians(r.getFacingAngle()))*distance);
		setRobotPosition(nX, nY, false);
		r.rotate(angle);
	}

}
